package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    @Async
    public void autoScanWmNews(Integer id)  {
        log.info("形参ID为"+String.valueOf(id));
        //1.查询自媒体文章
//        try {
//            Thread.sleep(3000);
//        }catch (Exception e){
//            System.out.println("睡眠异常");
//        }
        //未报告的异常错误java.lang.InterruptedException;

        WmNews wmNews = wmNewsMapper.selectById(id);
        System.out.println("查询ID为："+wmNews.getId());
        System.out.println("查询数据为："+wmNews);
        if (wmNews==null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
//        if (wmNews!=null){

        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本内容和图片
            //handleTextAndImages是本类的自定义方法，
            log.info("提取文本和图片");
            Map<String,Object> textAndImages= handleTextAndImages(wmNews);
            //2.审核文本内容，阿里云接口
            //handleTextScan是本类的自定义方法，
            log.info("审核文本");
            boolean isTextScan = handleTextScan((String) textAndImages.get("content"),wmNews);
            if (!isTextScan) return;
            
            //3.审核图片，阿里云接口
            //handleImageScan()是本类的自定义方法，
            log.info("审核图片");
            boolean isImageScan = handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if (!isImageScan) return;

            //4.审核成功，保存app端的相关文章数据
            //saveAppArticle是本类的自定义方法，
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存APP端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            //updateWmNews是本类的自定义方法，
            //既然审核中包含，为什么这里还有这个？
            // 因为审核提交那个没ID吗？
            log.info("更新wm_news表");
            updateWmNews(wmNews, (short) 9,"审核成功");

        }
    }
//}


//    @Qualifier("articleClient") //找不到这个名字的bean
//    @Resource(name = "articleClient")
//    @Resource
//@Autowired
    @Autowired(required = false)
    private IArticleClient articleClient;
    //添加报错IArticleClientFallback（按类型有多个，无法自动注入）
    //自动注入失败，找不到类，需要在启动类，手动扫描，
    //@EnableFeignClients(basePackages = "com.heima.apis")
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {

        log.info("saveAppArticle保存文章数据");

        ArticleDto dto=new ArticleDto();
        //属性的拷贝
        log.info("拷贝-同名属性的值-从形参wmNews到Article类型的dto");
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        log.info("设置布局");
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel=wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null){
            log.info("设置频道名");
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        log.info("设置作者ID");
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null){
            log.info("设置作者名");
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章ID
        if ((wmNews.getArticleId() != null)){
            log.info("设置文章ID");
            dto.setId(wmNews.getArticleId());
        }
        log.info("设置时间");
        dto.setCreatedTime(new Date());

        log.info("保存文章，保存文章配置，保存文章内容");
        ResponseResult responseResult = articleClient.saveArticle(dto);
        log.info("autoScanWmNews执行完毕，return前");
        //articleClient注入问题，远程调用执行错误，


        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;  //用于下载图片
    @Autowired
    private GreenImageScan greenImageScan;
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        log.info("审核图片");

        //图片为空，必然审核通过，直接返回true即可，
        if (images == null || images.size() == 0 ){
            return flag;
        }

        //图片去重，distinct()去重，
        // 重复图片没必要重复审核，
        images=images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();

        //下载图片，根据url列表，从minio
        //图片被存入字节数组的链表中，
        for (String image : images) {
            //来自heima-leadnews-basic下属heima-leadnews-basic
            byte[] bytes = fileStorageService.downLoadFile(image);
            imageList.add(bytes);
        }

        //审核图片
        try {
            //源于heima-leadnews-common的aliyun文件夹，这两个类的拷贝的，自定义？官方示例？太复杂没必要学？
            Map map = greenImageScan.imageScan(imageList);
            //审核失败
            if (map !=null){
                if (map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews(wmNews, (short) 2,"图片违规");
                }
            }
            //需要人工复核
            if (map !=null){
                if (map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews(wmNews, (short) 3,"图片需要复核");
                }
            }

        } catch (Exception e) {
            flag=false;
            log.info("阿里云图片审核报错了,错误信息如下");
//            java.net.ConnectException: Connection refused: connect
//            java.lang.RuntimeException: upload file fail.
            e.printStackTrace();
//            flag = true;    //无企业账号，假装审核通过
        }
        log.info("try/catch之后，执行了");
        log.info("没有企业账号，没有审核权限，模拟审核结果");
        log.info("修改审核结果为true");
        flag = true;
        return flag;
    }


    private GreenTextScan greenTextScan;
    //审核纯文本内容
    private boolean handleTextScan(String content, WmNews wmNews) {
        log.info("审核文本");

        boolean flag = true;

        //本文内容为空，必然审核通过，直接返回true即可，
        if ((wmNews.getTitle()+"-"+content).length() == 0){
            return flag;
        }

        try {
            Map map=greenTextScan.greeTextScan(wmNews.getTitle()+"-"+content);
            //审核失败
            if (map !=null){
                if (map.get("suggestion").equals("block")){
                    flag=false;
                    updateWmNews(wmNews, (short) 2,"文章内容存在违规");
                }
            }
            //需要人工复核
            if (map !=null){
                if (map.get("suggestion").equals("review")){
                    flag=false;
                    updateWmNews(wmNews, (short) 3,"文章内容敏感需要复核");
                }
            }
        } catch (Exception e) {
            flag=false;
            log.info("阿里云文本审核报错了,错误信息如下");
//            java.lang.NullPointerException
            e.printStackTrace();
        }
        log.info("try/catch之后，执行了");
        log.info("没有企业账号，没有审核权限，模拟审核结果");
        log.info("修改审核结果为true");
        flag = true;
        return flag;
    }

    private void updateWmNews(WmNews wmNews,short status,String reason) {
        log.info("更新wm_news表");
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    //1.只是 从自媒体内容中提取 纯文本内容和图片
    //2.提取封面图片
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        log.info("提取文本和图片");

        //存储纯文本内容
        StringBuilder stringBuilder=new StringBuilder();
        List<String> images=new ArrayList<>();

        //1.从自媒体内容中提取纯文本内容和图片
        if (StringUtils.isNotBlank(wmNews.getContent())){
            //把JSON变成Map链表
            List<Map> maps= JSONArray.parseArray(wmNews.getContent(),Map.class);
            for (Map map:maps) {
                //把map链表变成字符串，
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        //2.提取封面图片
        //参数校验，不为空
        log.info("提取封面");
        if (StringUtils.isNotBlank(wmNews.getImages())){
            //Images是封面图片，区别于content里面的image，
            String[] split=wmNews.getImages().split(",");
            //split() 方法根据匹配给定的正则表达式来拆分字符串。
            //把封面图片，也加入存储图片的字符串链表
            images.addAll(Arrays.asList(split));
        }

        //为什么用object不用泛型，不能嵌套吗？还是嫌麻烦？
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }


}
